package com.yicheng.statistics.repo.cassandra
import java.util.Date

import scala.collection.JavaConversions._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

import com.datastax.driver.core.Row
import com.datastax.driver.core.Statement
import com.datastax.driver.core.querybuilder.{ QueryBuilder => qb }
import com.datastax.driver.core.utils.UUIDs
import com.carcloud.gateway.bean.data.DataInfo.DataDetail.DataVehicle
import  com.carcloud.gateway.bean.data
import com.carcloud.gateway.bean.data.DataInfo.DataDetail
import com.yicheng.statistics.common.CommonUtils

/**
 * 
 */
object DataInfoDB {
  
  lazy val table = "t_data_info"

  import CassandraDB._
  import CassandraHelper._
  
  def fromRow(row: Row) = {
    try{
    println(CommonUtils.bytes2Hex(row.getBytes("data_detail").array()))
    com.yicheng.statistics.repo.model.Data.DataInfo(
      row.getInt("device_type"),
      row.getString("device_id"),
      row.getString("sub_device"),
      new Date(UUIDs.unixTimestamp(row.getUUID("data_time"))),
      row.getInt("data_type"),
      data.DataVehicle.parseFrom(row.getBytes("data_detail").array())
    )  
    }catch {
      case ex: Throwable => 
        println(s"dataInfo fromRow failed: $ex")
        //com.yicheng.statistics.repo.model.Data.DataInfo()
    }
  }

  def list(deviceType: Int, deviceId: String, start: Date, end: Date): Future[Seq[com.yicheng.statistics.repo.model.Data.DataInfo]] = {
    val query: Statement = qb.select()
      .from(keyspace, table)
      .where(qb.eq("device_id", deviceId))
      .and(qb.eq("device_type", deviceType))
      .and(qb.gte("data_time", UUIDs.startOf(start.getTime())) )
      .and(qb.lte("data_time", UUIDs.startOf(end.getTime())))
      .orderBy(qb.desc("data_time"))
    executeAsync(query).asScala.map(_.map(fromRow).toSeq)
  }
}